package com.sntk.organauthomanager.domain.model;

import com.sntk.organauthomanager.infrastructure.exception.DataEmptyException;
import com.sntk.organauthomanager.infrastructure.exception.ObjectExistedException;
import lombok.Getter;
import org.springframework.util.StringUtils;

import java.util.HashSet;
import java.util.Set;

/**
 * @ClassName: UserAffiliate
 * @author: wgchao
 * @createTime: 2020/9/9 8:53 AM
 * @Description: 用户关联机构
 */
@Getter
public class UserAffiliate extends AggregateRoot {

    //账户
    private String uname;

    //关联机构
    private Set<AffiliateInfo> affiliates;

    public UserAffiliate(String uname, Set<AffiliateInfo> affiliates) {
        if(StringUtils.isEmpty(uname)){
            throw new DataEmptyException("账户缺失");
        }
        this.uname = uname;
        this.affiliates = affiliates;
    }

    public void addAffiliate(AffiliateInfo affiliateInfo){
        if(isAffiliates(affiliateInfo.getInstitutionNumber())){
            throw new ObjectExistedException("用户已关联过该机构");
        }
        if(this.affiliates == null){
            this.affiliates = new HashSet<>();
        }
        this.affiliates.add(affiliateInfo);
    }

    /**
     * 判断机构是否为用户关联机构
     * @param institutionNumber
     * @return
     */
    public boolean isAffiliates(String institutionNumber){
        if(findByOrgan(institutionNumber) != null){
            return true;
        }
        return false;
    }

    public AffiliateInfo findByOrgan(String institutionNumber){
        if(this.affiliates ==null || this.affiliates.isEmpty()){
            return null;
        }
        for(AffiliateInfo affiliateInfo : affiliates){
            if(affiliateInfo.getInstitutionNumber().equals(institutionNumber)){
                return affiliateInfo;
            }
        }
        return null;
    }
}
